// pages/home/playBack/playBack.js
var t = require("../../../utils/formate.js"), a = require("../../../utils/util.js"), e = getApp().steps, i = getApp(), n = (getApp().getPromission,
  getApp().getAccessToken);

Page({

  /**
   * 页面的初始数据
   */
  data: {
    lat: "",
    lng: "",
    dateStart: "",
    dateEnd: "",
    timeStart: "00:00",
    timeEnd: "00:00",
    disabled: !0,
    sign: !0,
    imei: "",
    playData: {},
    playInterval: null,
    height: "0.8",
    content: "",
    i: 0,
    fontStyle: [],
    playSpeed: 500,
    play_img: "/images/" + i.system.image_prefix + "/play.png",
    playStatus: !0,
    adress: "",
    step: "1",
    dataStyle: "background:#f8f9fb;color:#888;margin-bottom:5px",
    picker: null,
    date: "",
    checkBox: "1",
    markers: [{}, {}, {}],
    polyline: [],
    controls: [],
    scrollTop: 0,
    baseLocation: 0,
    array: ["北斗+GPS", "北斗+GPS+WIFI", "北斗+GPS+基站+WIFI"],
    baseColor: i.system.color,
    playColor: i.system.playColor
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (a) {
    for (var e = [], n = 0; n < 6; n++) e[n] = 1 == n;
    wx.openBluetoothAdapter ? wx.openBluetoothAdapter() : wx.showModal({
      title: "提示",
      content: "当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。"
    }), wx.createSelectorQuery().select("#map").boundingClientRect(function (t) {
      var a = g.data, e = a.controls;
      a.sign;
      e.push({
        id: 1,
        iconPath: "/images/" + i.system.image_prefix + "/time_selsect.png",
        position: {
          left: t.width - 65,
          top: 45,
          width: 50,
          height: 50
        },
        clickable: !0
      }), g.setData({
        controls: e
      });
    }).exec(), this.playInterval = null;
    for (var s = this.data, l = s.fontStyle, r = s.sign, o = (s.height, s.playStatus), p = s.play_img, n = 0; n < 5; n++) l[n] = 1 == n ? "fontStyleT" : "fontStyle";
    var c = a.imei, u = a.lat, d = a.lng, g = this, h = t.initYearMonthDay(), m = t.initYearMonthDay(), f = t.getTime(1, 0, 1), y = t.getTime(0, 0, 1), v = t.caluateTime(1);
    this.setData({
      dateStart: h,
      dateEnd: m,
      radio: e,
      timeStart: f,
      timeEnd: y,
      date: v,
      imei: c,
      lat: u,
      lng: d,
      fontStyle: l,
      sign: r,
      playStatus: o,
      play_img: p
    }, function () { });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    this.mapCtx = wx.createMapContext("map"), this.getHeight();
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    clearInterval(this.playInterval);
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    clearInterval(this.playInterval);
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

  setMap: function () { },
  bindDateChange: function (t) {
    this.setData({
      dateStart: t.detail.value
    });
  },
  bindDateEnd: function (t) {
    this.setData({
      dateEnd: t.detail.value
    });
  },
  checkboxChange: function (a) {
    for (var e = this.data, i = e.fontStyle, n = e.radio, s = 0; s < 6; s++) s == a.detail.value ? (i[s] = "fontStyleT",
      n[s] = !0) : (i[s] = "fontStyle", n[s] = !1);
    var l = t.caluateTime(Number(a.detail.value));
    5 == a.detail.value ? this.setData({
      disabled: !1,
      dataStyle: "margin-bottom:5px; color: black",
      picker: "rgba(0,0,0,0.16)"
    }) : this.setData({
      disabled: !0,
      dataStyle: "background:#f8f9fb;color:#888;margin-bottom:5px",
      picker: null
    });
    var r = null;
    4 === Number(a.detail.value) && (r = 3600), this.setData({
      date: l,
      fontStyle: i,
      radio: n,
      checkBox: a.detail.value,
      duration: r
    });
  },
  bindTimeChangeStart: function (t) {
    this.setData({
      timeStart: t.detail.value
    });
  },
  bindTimeChangeEnd: function (t) {
    this.setData({
      timeEnd: t.detail.value
    });
  },
  controltap: function (t) {
    var a = this, e = this.data, n = e.controls;
    e.playInterval;
    this.playInterval && clearInterval(this.playInterval);
    var s = "/images/" + i.system.image_prefix + "/play.png";
    this.setData({
      sign: !0,
      controls: n,
      playStatus: !0,
      play_img: s,
      height: "0.8",
      polyline: [],
      markers: [{}, {}, {}],
      i: 0,
      content: ""
    }, function () {
      return a.getHeight();
    });
  },
  switchChange: function (t) {
    var a = t.detail.value;
    this.setData({
      baseLocation: a
    });
  },
  play: function () {
    var a = this, e = this.data, n = e.markers, s = (e.playInterval, a.infoData), l = [], r = this.data.i, o = s.length;
    if (this.playIntervall && clearInterval(this.playInterval), r >= o - 1) {
      clearInterval(this.playInterval);
      var p = "/images/" + i.system.image_prefix + "/play.png";
      a.setData({
        polyline: [],
        markers: [{}, {}, {}],
        i: 0,
        play_img: p
      });
    }
    if (0 == (r = this.data.i)) {
      wx.showLoading({
        title: "加载中"
      });
      var c = s[0], u = s[o - 1], d = [];
      (n = this.data.markers)[1].iconPath = "/images/" + i.system.image_prefix + "/start.png",
        n[1].id = 1, n[1].latitude = c.lat, n[1].longitude = c.lng, n[1].width = 20, n[1].height = 20,
        n[2].iconPath = "/images/" + i.system.image_prefix + "/end.png", n[2].id = 2, n[2].latitude = u.lat,
        n[2].longitude = u.lng, n[2].width = 20, n[2].height = 20;
      var g = [];
      s.map(function (t, a) {
        g.push({
          longitude: s[a].lng,
          latitude: s[a].lat
        }), 1 == t.status && d.push({
          runData: t,
          i: a
        });
      }), l.push({
        points: g,
        color: "#FF0000DD",
        width: 4
      }), a.mapCtx.includePoints({
        padding: [10, 10, 10, 10],
        points: g
      });
      n = this.data.markers;
      d.map(function (e, s) {
        if (d[s + 1]) {
          var l = (d[s + 1].runData.gpsTime - d[s].runData.gpsTime) / 1e3 / 60, r = t.getFormattedTime((d[s + 1].runData.gpsTime - d[s].runData.gpsTime) / 1e3);
          if (l >= 3) {
            var o = d[s + 1].runData.lat, p = d[s + 1].runData.lng;
            new Promise(function (t, a) {
              wx.getStorage({
                key: "accessToken",
                success: function (a) {
                  a.data && wx.request({
                    url: i.system.app_url_prefix + "/rest/location/detail?lat=" + o + "&lng=" + p + "&accessToken=" + a.data,
                    method: "GET",
                    header: {
                      Accept: "application/json",
                      "Content-Type": "application/json; charset=utf-8"
                    },
                    success: function (a) {
                      a.data && t(a.data.formatted_address + "" + a.data.sematic_description);
                    },
                    fail: function (t) { }
                  });
                },
                fail: function (t) { }
              });
            }).then(function (l) {
              var o = " 停留时长" + r + "\n " + t.formatTime(d[s].runData.gpsTime, "Y/M/D h:m:s") + " - " + t.formatTime(d[s + 1].runData.gpsTime, "Y/M/D h: m:s") + "\n" + l;
              n.push({
                iconPath: "/images/" + i.system.image_prefix + "/statyPoint.png",
                id: s + "001",
                latitude: e.runData.lat,
                longitude: e.runData.lng,
                height: 18,
                width: 15,
                callout: {
                  content: o,
                  color: "#000000",
                  fontSize: 14,
                  borderRadius: 10,
                  display: "BYCLICK",
                  padding: 5
                }
              }), a.setData({
                markers: n
              });
            });
          }
        }
      }), this.setData({
        scale: 18,
        polyline: l,
        lat: s[0].lat,
        lng: s[0].lng
      }, function () {
        return wx.hideLoading();
      });
    }
    var h = this.data, m = h.playSpeed, n = h.markers, a = this;
    this.playInterval = setInterval(function () {
      var t = a.data.i;
      if (t < o - 1) {
        0 == n[0].id ? a.mapCtx.translateMarker({
          markerId: 0,
          duration: 1,
          destination: {
            latitude: Number(s[t].lat),
            longitude: Number(s[t].lng)
          }
        }) : (n[0].iconPath = "/images/" + i.system.image_prefix + "/where.png", n[0].id = 0,
          n[0].latitude = s[t].lat, n[0].longitude = s[t].lng, n[0].width = 15, n[0].height = 15,
          n[0].anchor = {
            x: .5,
            y: .5
          }, a.setData({
            markers: n
          }));
        var e = s[t].lat, l = s[t].lng;
        a.mapCtx.getRegion({
          success: function (t) {
            var i = t.southwest.latitude, n = t.southwest.longitude, s = t.northeast.latitude, r = t.northeast.longitude;
            (e <= i || e >= s || l >= r || l <= n) && a.setData({
              lat: e,
              lng: l
            });
          }
        }), a.shuwInfo(s, t);
      } else if (t == o - 1) new Promise(function (e) {
        a.mapCtx.translateMarker({
          markerId: 0,
          duration: 1,
          destination: {
            latitude: Number(s[t].lat),
            longitude: Number(s[t].lng)
          }
        }), e();
      }).then(function () {
        clearInterval(a.playInterval);
        var t = "/images/" + i.system.image_prefix + "/play.png";
        a.setData({
          play_img: t,
          playStatus: !0
        });
      }), a.shuwInfo(s, t); else {
        clearInterval(a.playInterval);
        var r = "/images/" + i.system.image_prefix + "/play.png";
        a.setData({
          play_img: r,
          playStatus: !0
        });
      }
      t++ , a.setData({
        i: t
      });
    }, m);
  },
  playStart: function () {
    clearInterval(this.playInterval);
    var t = this.data.playStatus;
    if (this.infoData) {
      var a;
      t ? (t = !1, a = "/images/" + i.system.image_prefix + "/stop.png", this.infoData.length > 0 && this.play()) : (t = !0,
        a = "/images/" + i.system.image_prefix + "/play.png"), this.setData({
          playStatus: t,
          play_img: a
        });
    } else wx.showToast({
      title: "没有数据",
      image: "/images/" + i.system.image_prefix + "/err.png",
      duration: 1500
    });
  },
  sliderChange: function (t) {
    n = this.data.playStatus;
    if (this.data.polyline.length > 0) {
      clearInterval(this.playInterval);
      var a = this.data.playData.deviceStatusBeanList[t.detail.value], e = this.data.playData.deviceStatusBeanList;
      this.mapCtx.translateMarker({
        markerId: 0,
        duration: 1,
        destination: {
          latitude: Number(a.lat),
          longitude: Number(a.lng)
        }
      }), this.shuwInfo(e, t.detail.value);
      var n = !0, s = "/images/" + i.system.image_prefix + "/play.png";
      this.setData({
        play_img: s,
        playStatus: n,
        i: t.detail.value,
        lat: a.lat,
        lng: a.lng
      });
    }
  },
  calcuteMil: function (a, e) {
    var i = 0;
    return a.map(function (n, s) {
      s < e && (i += t.getDistance({
        lat: a[s].lat,
        lng: a[s].lng
      }, {
          lat: a[s + 1].lat,
          lng: a[s + 1].lng
        }));
    }), (i / 1e3).toFixed(2);
  },
  shuwInfo: function (e, i) {
    var n = a.getCourse(e[i].direction, e[i].speed) ? a.getCourse(e[i].direction, e[i].speed) : "--", s = t.formatTime(e[i].transport_time, "Y-M-D h:m:s") + "速度" + e[i].speed + "km/h 里程" + this.calcuteMil(e, i) + "km  航向:" + n;
    this.setData({
      content: s
    });
  },
  cancle: function () {
    this.setData({
      sign: !1,
      height: "1.8"
    }, function () { }), this.getHeight();
  },

  affirm: function () {
    var t = this;
    this.timeFlag = 0, this.setData({
      sign: !1,
      height: "1.8",
      i: 0
    }, function () {
      return t.playData();
    }), this.getHeight();
  },

  playData: function () {
    var a, e = this, s = this.data, l = s.dateStart, r = s.duration, o = s.dateEnd, p = s.timeStart, c = s.timeEnd, u = s.date, d = s.baseLocation, g = s.checkBox, h = s.imei, m = Date.parse(new Date());
    if (u ? (a = u, "2" == g ? (o = t.initYearMonthDay(0, 0, -1), c = "23:59:59") : "3" == g && (o = t.initYearMonthDay(0, 0, -2),
      c = "23:59:59"), m = Date.parse(o.replace(/-/g, "/") + " " + c)) : (a = Date.parse(new Date(l.replace(/-/g, "/") + " " + p)),
        m = Date.parse(o.replace(/-/g, "/") + " " + c)), a > m) return wx.showModal({
          title: "提示",
          showCancel: !1,
          content: "开始时间不能大于结束时间",
          success: function (t) {
            t.confirm || t.cancel;
          }
        }), void this.setData({
          sign: !0,
          height: "0.8",
          i: 0
        });

    var n = "0011";
    switch (d) {
      case "1":
        n = "0111";
        break;

      case "2":
        n = "1111";
        break;

      default:
        n = "0011";
    }
    var s = i.system.app_url_prefix + "/weapp/transport/gj/query?vehicleId=" + h + "&startTime=" + a / 1e3 + "&endTime=" + m / 1e3
    r && (s += "&duration=" + r)

    var startTime = format(a)
    var endTime = format(m)
    wx.request({
      url: s,
      method: "POST",
      data: { "pageSize": 1000, "pageNum": 1, "data": { "start_time": startTime, "end_time": endTime}},
      header: {
        Accept: "application/json",
        "Content-Type": "application/json; charset=utf-8"
      },
      success: function (t) {
        let data = t.data
        let code = parseInt(data.code)
        if (code == 0) {
          let list = data.list
          var a = list.length - 1;
          if (list.length <= 0) {
            wx.showToast({
              title: "没有数据",
              image: "/images/" + i.system.image_prefix + "/err.png",
              duration: 3e3
            });
            var n = "/images/" + i.system.image_prefix + "/play.png";
            return void e.setData({
              playStatus: !0,
              play_img: n
            });
          }
          e.infoData = list, e.setData({
            playData: t.data,
            endStep: a
          }, e.playStart());
        }
      },
      fail: function (t) { }
    });

    // n(), 
    // wx.getStorage({
    //   key: "accessToken",
    //   success: function (t) {
    //     if (t.data) {
    //       var n = "0011";
    //       switch (d) {
    //         case "1":
    //           n = "0111";
    //           break;

    //         case "2":
    //           n = "1111";
    //           break;

    //         default:
    //           n = "0011";
    //       }
    //       var s = i.system.app_url_prefix + "/rest/user2c/device/track/" + h + "?startTime=" + a / 1e3 + "&endTime=" + m / 1e3 + "&mapType=" + i.mapType + "&accessToken=" + t.data + "&locationType=" + n;
    //       r && (s += "&duration=" + r)
    //     }
    //   },
    //   fail: function (t) { }
    // });
  },
  playSpeed: function () {
    var t, a, i = this;
    switch (e) {
      case 0:
        t = "2", e = 1, a = 300;
        break;

      case 1:
        t = "4", e = 2, a = 75;
        break;

      case 2:
        t = "1", e = 0, a = 500;
    }
    var n = this.data.playStatus;
    this.setData({
      step: t,
      playSpeed: a
    }, function () {
      n || (clearInterval(i.playInterval), i.play());
    });
  },
  bindtap: function () { },
  getHeight: function () {
    var t = this;
    wx.createSelectorQuery().select("#map").boundingClientRect(function (a) {
      t.setData({
        maskHeight: a.height
      });
    }).exec();
  },
  bindupdated: function () { },
  bindPickerLocation: function (t) {
    this.setData({
      baseLocation: t.detail.value
    });
  }
})

function add0(m) { return m < 10 ? '0' + m : m }
function format(shijianchuo) {
  //shijianchuo是整数，否则要parseInt转换
  var time = new Date(shijianchuo);
  var y = time.getFullYear();
  var m = time.getMonth() + 1;
  var d = time.getDate();
  var h = time.getHours();
  var mm = time.getMinutes();
  var s = time.getSeconds();
  return y + '-' + add0(m) + '-' + add0(d) + ' ' + add0(h) + ':' + add0(mm) + ':' + add0(s);
}